from django.contrib.auth import logout
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from blog.models import User
import hashlib


# from django.dispatch import Signal

# Create your views here.


def login_page(request):
    if request.method == 'GET':
        # 先去sessionk看username,uuid,有,登录成功
        # 去cookies看username,uuid，有，登录成功
        if request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('已登录')
        elif request.COOKIES.get('username') and request.COOKIES.get('uuid'):
            return HttpResponse('已登录')
        else:
            return render(request, 'login.html')

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse('用户名不存在')

        # if not user:
        #     return HttpResponse('用户名不存在')

        # 1.初始化2.password从字符串转为字节3.加密
        # 实例化对象，初始化
        md = hashlib.md5()
        # password从字符串转为字节
        md.update(password.encode())
        # hash进行加密，转成16进制
        password = md.hexdigest()

        if password != user.password:
            return HttpResponse('密码错误')

        request.session['username'] = username
        request.session['uuid'] = user.id

        resp = HttpResponse('登录成功')
        if 'remember' in request.POST:
            resp.set_cookie('username', username, 3600 * 24 * 7)
            resp.set_cookie('uuid', user.id, 3600 * 24 * 7)

        return resp


def reg_view(request):
    if request.method == "GET":
        return render(request, "register.html")
    elif request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        # print(f'加密后的密码是{password}!!!!!')
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')
        # m = hashlib.md5()
        # m.update(password.encode())
        # password = m.hexdigest()
        User.objects.create(username=username, password=password)
        # return.session['username'] = username
        # request.session['uid']=
        # return HttpResponse('注册成功')
        request.session['username'] = username
        return HttpResponseRedirect('/blog/index/')


def index(request):
    return render(request, 'index.html')


def login_view(request):
    logout(request)
    return HttpResponseRedirect('/blog/index/')
